package com.lesson05_JDBC;

import java.sql.*;

public class JDBCTest {
    public static void main(String[] args) {

        //genericMethod(); // 有SQL注入的危险
        genericMethod1();
    }

    /**
     * 解决SQL注入问题
     */
    private static void genericMethod1() {
        try {
            // 加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 通过驱动管理类DriverManager获取连接对象
            String url = "jdbc:mysql://rm-bp1534a9ofozwbb9p0o.mysql.rds.aliyuncs.com:3306/dmp_config?useSSL=false&serverTimezone=GMT%2B8";
            Connection connection = DriverManager.getConnection(url, "root", "dmp@Mysoft#2024");
            String sql = "select * from project where code like ? and rds_id=?";

            // 创建编译对象
            PreparedStatement pst = connection.prepareStatement(sql);
            // 设置参数
            pst.setString(1, "%han%");
            pst.setInt(2, 0);
            // 执行SQL语句并处理返回结果
            ResultSet resultSet = pst.executeQuery();
            // 把获取结果输出到控制台
            while (resultSet.next()) {
                System.out.println(resultSet.getString("code")+","
                        +resultSet.getString("name"));
            }

            // 释放操作资源
            resultSet.close();
            pst.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void genericMethod() {
        try {
            // 加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 通过驱动管理类DriverManager获取连接对象
            String url = "jdbc:mysql://rm-bp1534a9ofozwbb9p0o.mysql.rds.aliyuncs.com:3306/dmp_config?useSSL=false&serverTimezone=GMT%2B8";
            Connection connection = DriverManager.getConnection(url, "root", "dmp@Mysoft#2024");
            // 创建编译对象
            Statement statement = connection.createStatement();
            String name = "han";
            // String sql = "select * from t_user where user_name like '%"+name+"%'";
            // SQL注入问题
            String sql = String.format("select * from t_user where user_name like '%s' and user_gender=%s","%hanmei%' -- ","女");
            // 执行SQL语句并处理返回结果
            ResultSet resultSet = statement.executeQuery(sql);
            // 把获取结果输出到控制台
            while (resultSet.next()) {
                System.out.println(resultSet.getString("user_name")+","
                        +resultSet.getString("user_gender"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
